#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <vector>

const int threadnum = 5;

class Result
{
    public:
    Result(){}
    ~Result(){}
    void SetResult(int a,const std::string & threadname)
    {
        _val = a;
        _threadname = threadname;
    }
    void Print()
    {
        std::cout << _threadname << ":" << _val << std::endl;
    }
  private:
  std::string _threadname;
  int _val;  
};
class Task
{
    public:
    Task(int x,int y)
    :_x(x),_y(y)
    {}
    int Execute()
    {
        return _x + _y;
    }
    ~Task()
    {}
    private:
    int _x;
    int _y;
};
class ThreadData
{
    public:
    ThreadData(int x,int y,const std::string &threadname)
    :_threadname(threadname),_t(Task(x,y))
    {
        
    }
    std::string threadname()
    {
        return _threadname;
    }
    int run()
    {
        return _t.Execute();
    }
    ~ThreadData(){}
    private:
    std::string _threadname;
    Task _t;
};
void* HandleTask(void* args)
{
    ThreadData* td = static_cast<ThreadData*>(args);

    std::string name = td->threadname();

    int val = td->run();
    Result* res = new Result();
    res->SetResult(val,name);

    delete td;

    return (void*)res;
}
int main()
{
    //多线程
    std::vector<pthread_t> threads;
    for(int i = 0;i < threadnum;++i)
    {
        char threadname[64];//为每一个线程命名
        snprintf(threadname,64,"Thread-%d",i+1);

        pthread_t tid;
        ThreadData* td = new ThreadData(10,20,threadname);
        pthread_create(&tid,nullptr,HandleTask,td);
        threads.push_back(tid);
    }

    std::vector<Result*> print_res;
    void* ret = nullptr;
    for(auto& tid:threads)
    {
        pthread_join(tid,&ret);
        print_res.push_back((Result*)ret);

    }

    for(auto& res:print_res)
    {
        res->Print();
        delete res;
    }
    return 0;
}

// void* HandleTask(void* args)
// {
//     //新线程
//     std::string threadname = (char*)args;
//     int cnt =5;
//     while(cnt)
//     {
//         sleep(1);
//         cnt--;
//     }
//     return (void*)111;
// }   

// int main()
// {
//     //主线程
//     //创建
//     pthread_t tid;
//     pthread_create(&tid,nullptr,HandleTask,(void*)"name");

//     //终止测试
//     sleep(1);
//     pthread_cancel(tid);
//     //等待
//     void* ret = nullptr;
//     int cnt =10;
//     while(cnt)
//     {
//         sleep(1);
//         cnt--;
//     }

//     int abc = pthread_join(tid,&ret);
//     std::cout << "abc->" << abc << "new thread ret->" << (long)ret << std::endl;
//     return 0;
// }
